package cn.chaos.bio01;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class TCPEchoClientNonblocking {

    public static void main(String[] args) throws IOException  {
        String server = "localhost";
        int port = 11111;
        
        byte[] argument = "创办《刊物》，呼吁民主".getBytes(StandardCharsets.UTF_8);
        
        // 创建 channel 并且设置为非阻塞
        SocketChannel clientChannel = SocketChannel.open();
        clientChannel.configureBlocking(false);
        
        // Initiate connection to server and
        // repeatedly poll until complete
        // 非阻塞式的 connect 调用可能会在连接建立之前返回
        if (!clientChannel.connect(new InetSocketAddress(server, port))) {
            while (!clientChannel.finishConnect()) {
                System.out.print("."); // Do someing else
            }
        }
        
        ByteBuffer writeBuf = ByteBuffer.wrap(argument);
        ByteBuffer readBuf = ByteBuffer.allocate(argument.length);
        
        int totalBytesRcvd = 0; // Total bytes received so far
        int bytesRcvd; // Bytes received in last read
        
        while (totalBytesRcvd < argument.length ) {
            if (writeBuf.hasRemaining()) {
                clientChannel.write(writeBuf);
            }
            if ((bytesRcvd = clientChannel.read(readBuf)) == -1) {
                throw new SocketException("Connection closed preematurely");
            }
            totalBytesRcvd += bytesRcvd;
            System.out.print("."); // Do something else
        }
        
        System.out.println("Received: "+ 
                new String(readBuf.array(), 0, totalBytesRcvd));
        clientChannel.close();
        
        
    }
}
